package com.chenjiajin.fastjson_test.TypeReference;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chenjiajin.domain.TestPoJo;

import java.util.ArrayList;
import java.util.List;

public class ListTest {

    // 演示: 在fastjson中提供了一个用于处理泛型反序列化的类TypeReference。
    // List<TestPoJo>
    public static void main(String[] args) {
        TestPoJo domain = new TestPoJo("as1111das", "fhgfgh", "utyuty", "opipi");
        TestPoJo domain2 = new TestPoJo("sda2222sd", "fhgfuyuyigh", "utyuty", "opipi");
        TestPoJo domain3 = new TestPoJo("fgh3333jgf", "fhgfgh", "utyuty", "opipi");
        TestPoJo domain4 = new TestPoJo("lk4444jl", "jklj", "utyuty", "opipi");
        List<TestPoJo> dataList = new ArrayList<>();
        dataList.add(domain);
        dataList.add(domain2);
        dataList.add(domain3);
        dataList.add(domain4);

        String str = JSON.toJSONString(dataList);

        //旧的解析方式:
        // List<TestPoJo> list = JSON.parseObject(str, List<TestPoJo>.class);  // 编译不允许

        // List list = JSON.parseObject(str, List.class);   // 只能返回List  泛型丢失
        //System.out.println("list = " + list);             // 直接打印可以
        //
        ////TestPoJo testPoJo = list.get(0);                // 试图拿出元素 将直接出现异常 com.alibaba.fastjson.JSONObject cannot be cast to com.chenjiajin.domain.TestPoJo
        //
        //Object object = list.get(0);
        //System.out.println(object);                       // 可以打印自定义对象的toString方法
        //
        //TestPoJo object1 = (TestPoJo) object;
        //System.err.println(object1);                      //试图强转时 将出现异常 com.alibaba.fastjson.JSONObject cannot be cast to com.chenjiajin.domain.TestPoJo


        //  List<TestPoJo> 带泛型解析
        List<TestPoJo> list = JSON.parseObject(str, new TypeReference<List<TestPoJo>>() {
        });
        list.forEach(System.out::println);

        TestPoJo testPoJo = list.get(0);
        System.err.println(testPoJo);


    }

}